package com.cyy.partner.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cyy.partner.common.Result;
import com.cyy.partner.pojo.News;
import com.cyy.partner.service.NewsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: cyy
 * @Date: 2024/5/24
 */
@RestController
@Api(tags = "公告管理相关接口")
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private NewsService newsService;

    /**
     * 公告列表
     * @param newsName
     * @return
     */
    @ApiOperation("公告列表接口")
    @GetMapping("/list")
    public Result<List<News>> list(@RequestParam(required = false) String newsName){
        System.out.println(newsName);
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(newsName!=null, News::getNewsName, newsName);
        queryWrapper.orderByDesc(News::getTime);
        List<News> list = newsService.list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 发布公告
     * @param news
     * @return
     */
    @ApiOperation("发布公告接口")
    @PostMapping("/add")
    public Result<String> add(@RequestBody News news){
        System.out.println(news);
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(News::getNewsName, news.getNewsName());
        News one = newsService.getOne(queryWrapper);
        if(one != null){
            return Result.error("该公告已发布");
        }
        news.setTime(LocalDateTime.now());
        newsService.save(news);
        return Result.success("公告发布成功");
    }

    /**
     * 根据id删除公告
     * @param id
     * @return
     */
    @ApiOperation("根据id删除公告接口")
    @DeleteMapping
    public Result<String> delete(Long id){
        System.out.println(id);
        News news = newsService.getById(id);
        if(news == null){
            return Result.error("该公告不存在");
        }
        newsService.removeById(id);
        return Result.success("公告已成功删除");
    }
}
